package com.pro.addresslist.ui.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.pro.addresslist.R;
import com.pro.addresslist.dal.bll.ContactInfoBLL;
import com.pro.addresslist.dal.bll.IPMACBLL;
import com.pro.addresslist.dal.model.ContactInfo;
import com.pro.addresslist.dal.model.ContactInfoBySqlite;
import com.pro.addresslist.dal.model.IPMAC;
import com.pro.addresslist.dal.model.SortModel;
import com.pro.addresslist.sqllite.ContactInfoServise;
import com.pro.addresslist.tools.NetUtil;
import com.pro.addresslist.tools.constantUtil;
import com.pro.addresslist.ui.activity.ContactsActivity.ReceiveBroadCast;
import com.pro.addresslist.ui.adapter.CommonAdapter;
import com.pro.addresslist.ui.adapter.ViewHolder;
import com.pro.addresslist.ui.common.BaseActivity;
import com.pro.addresslist.ui.common.MyApplication;
import com.pro.addresslist.ui.view.CharacterParser;
import com.pro.addresslist.ui.view.ClearEditText;
import com.pro.addresslist.ui.view.PinyinComparator;
import com.pro.addresslist.ui.view.PopMenu;
import com.pro.addresslist.ui.view.SideBar;

public class HomeActivity extends BaseActivity {
	private List<Object[]> listitm = new ArrayList<Object[]>();
	private PopMenu pop;
	private SimpleAdapter adapter = null;
	private List<Map<String, Object>> listitems = new ArrayList<Map<String, Object>>();
	private ListView listview, gr;
	//
	private LinearLayout layout;
	private long mExitTime;
	
	private int posiont=0;

	private TextView tvLetter;
	private TextView tvTitle;
	private TextView img;
	private CommonAdapter<ContactInfoBySqlite> adapterSort;

	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<ContactInfoBySqlite> SourceDateList = new ArrayList<ContactInfoBySqlite>();

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	@Override
	public int getLayout() {
		return R.layout.home;
	}

	@Override
	public void OnActCreate(Bundle savedInstanceState) {
		initView();
		initItemListener();
		initGesture();
		new Thread(new myThreadNoGroup()).start();
		showProgressDialog();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		new Thread(new myThreadNoGroup()).start();
		showProgressDialog();
	}
	class myThreadNoGroup implements Runnable {
		@Override
		public void run() {
			ContactInfoServise conSer=new ContactInfoServise(mContext);
			List<ContactInfoBySqlite> listcon=conSer.SelectContactByNoGroup();
			Message message = new Message();   
	        message.what = constantUtil.Num_SelectContactByNoGroup;
	        message.obj=listcon;
	        mHandler.sendMessage(message);
		}
	}


	private void initGesture() {

		layout = (LinearLayout) findViewById(R.id.layout);
		gr.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onScroll(AbsListView arg0, int firstVisibleItem,
					int arg2, int arg3) {
				if (firstVisibleItem >= 1) {
					layout.setVisibility(View.VISIBLE);
				} else {

					layout.setVisibility(View.GONE);
				}

			}
		});
	}

	private void initItemListener() {
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (listitems.get(arg2).get("title").equals("全部人员")) {
					Intent intent = new Intent(HomeActivity.this,
							ContactsActivity.class);
					startActivity(intent);
				}
				if (listitems.get(arg2).get("title").equals("分类管理")) {
					Intent intent = new Intent(HomeActivity.this,
							managementActivity.class);
					startActivity(intent);
				}
				if (listitems.get(arg2).get("title").equals("生日提醒")) {
					Intent intent = new Intent(HomeActivity.this,
							BirthdayReminder.class);
					startActivity(intent);
				}
			}
		});
	}

	private void initView() {
		setTtile("大爱通");
		setRightImage(R.drawable.icon_more, this);
		setViewClick(R.id.iv_title_right_image);
		setViewClick(R.id.id_tab_frd);
		setViewClick(R.id.id_tab_address);
		// 主页listview布局
		listview = (ListView) findViewById(R.id.lvhome);
		View header = View.inflate(this, R.layout.stick_action, null);// 头部内容
		listview = (ListView) header.findViewById(R.id.lvhome);
		int[] imageld = new int[] { R.drawable.icon_allpeople,
				R.drawable.icon_classify, R.drawable.icon_birthday };

		String[] title = new String[] { "全部人员", "分类管理", "生日提醒" };
		for (int i = 0; i < imageld.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("image", imageld[i]);
			map.put("title", title[i]);
			listitems.add(map);
		}
		adapter = new SimpleAdapter(this, listitems, R.layout.home_itmes,
				new String[] { "title", "image" }, new int[] { R.id.title,
						R.id.image });
		listview.setAdapter(adapter);
		
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();
		gr = (ListView) findViewById(R.id.country_lvcountry);
		gr.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				if (position > 1) {
					// Toast.makeText(getApplication(),
					// SourceDateList.get(position-2).getName(),
					// Toast.LENGTH_SHORT).show();
					Intent intent = new Intent(mContext,
							PersonalInformationActivity.class);
					intent.putExtra("contactID",
							SourceDateList.get(position - 2).get_id()+"");
					startActivity(intent);
				}
			}
		});
		gr.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				posiont = arg2;
				gr.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
					@Override
					public void onCreateContextMenu(ContextMenu arg0,
							View arg1, ContextMenuInfo arg2) {
						MenuInflater inflator = new MenuInflater(
								HomeActivity.this);
						inflator.inflate(R.menu.relation_menu, arg0);
					}
				});
				return false;
			}
		});
		adapterSort = new CommonAdapter<ContactInfoBySqlite>(HomeActivity.this,
				SourceDateList, R.layout.item) {

			@Override
			public void convert(ViewHolder holder, ContactInfoBySqlite t) {
				int position = holder.getPosition();
				tvLetter = (TextView) holder.getView(R.id.catalog);
				tvTitle = (TextView) holder.getView(R.id.title);
				img = (TextView) holder.getView(R.id.img);
				// 根据position获取分类的首字母的char ascii值
				int section = getSectionForPosition(position);
				// 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
				if (position == getPositionForSection(section)) {
					tvLetter.setVisibility(View.VISIBLE);
					tvLetter.setText(t.get_NAMEPY());
				} else {
					tvLetter.setVisibility(View.GONE);
				}
				tvTitle.setText(t.get_Name());
				img.setText(t.get_Name().substring(0, 1));
			}
		};
		gr.addHeaderView(header);// 添加头部
		gr.addHeaderView(View.inflate(this, R.layout.gr_listview_header, null));
		gr.setAdapter(adapterSort);
		

	}
	// 长按菜单响应函数
	@Override
	public boolean onContextItemSelected(MenuItem item){
		switch (item.getItemId()) {
		case R.id.del:
			int id=SourceDateList.get(posiont-2).get_id();
			String conId=SourceDateList.get(posiont-2).get_ContactID();
			ContactInfoServise ser = new ContactInfoServise(mContext);
			int state=ser.SelectStateByid(id);
			if(state==1){
				Boolean re=ser.DelContactByIDTrue(id);
				if(re){
					Toast.makeText(mContext,"删除成功！",Toast.LENGTH_SHORT).show();
					SourceDateList.remove(posiont-2);
					adapterSort.notifyDataSetChanged();
				}
				else {
					Toast.makeText(mContext,"删除失败！",Toast.LENGTH_SHORT).show();
				}
			}
			else{
				if(NetUtil.isNetworkAvailable(mContext)){
					ContactInfoBLL.DelContactByID(mContext, conId, id,mHandler);
				}
				else{
					Toast.makeText(mContext,"当前无网络，不能执行删除！",Toast.LENGTH_SHORT).show();
				}
			}
			break;
		case R.id.updata:
			Intent in = new Intent(HomeActivity.this, NewContactsActivity.class);
			in.putExtra("actions", "edtcon");
			in.putExtra("conid", SourceDateList.get(posiont-2).get_id());
			startActivity(in);
			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	public void OnViewClick(View v) {
		switch (v.getId()) {
		case R.id.iv_title_right_image:
			final ImageView dddd = (ImageView) findViewById(R.id.iv_title_right_image);
			listitm.clear();
			listitm.add(new Object[] { "新建联系人", R.drawable.icon_adduser1 });
			listitm.add(new Object[] { "绑定手机", R.drawable.icon_bindphone });
			listitm.add(new Object[] { "上传与同步", R.drawable.icon_synchronize });
			listitm.add(new Object[] { "退出系统", R.drawable.icon_exit });

			pop = new PopMenu(HomeActivity.this, R.layout.test, R.id.listv,
					R.layout.test_itmes, listitm, R.id.d1, R.id.ImgVleft, 400);
			pop.showAsDropDown(dddd, -100, 0, true);
			pop.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					switch (arg2) {
					case 0:
						pop.dismiss();
						Intent newcont = new Intent();
						newcont.setClass(getApplicationContext(),
								NewContactsActivity.class);
						startActivity(newcont);
						break;
					// 绑定手机
					case 1:
						pop.dismiss();
						Intent boldPhone = new Intent();
						boldPhone.setClass(getApplicationContext(),
								MacAddressActivity.class);
						startActivity(boldPhone);
						break;
						//数据同步
					case 2:
						pop.dismiss();
						Intent synchronize = new Intent();
						synchronize.setClass(getApplicationContext(),
								SynchronizeActivity.class);
						startActivity(synchronize);
						break;
					// 退出系统
					case 3:
						MyApplication.getInstance().quit();
					default:
						break;
					}
				}
			});
			break;
		case R.id.id_tab_frd:
			Intent in = new Intent(HomeActivity.this, FriendActivity.class);
			startActivity(in);
			break;
		case R.id.id_tab_address:
			Intent CameraIn = new Intent(HomeActivity.this,
					CameraActivity.class);
			startActivity(CameraIn);
			break;
		}

	}

	/**
	 * 根据ListView的当前位置获取分类的首字母的char ascii值
	 */
	public int getSectionForPosition(int position) {
		return SourceDateList.get(position).get_NAMEPY().charAt(0);
	}

	/**
	 * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
	 */
	public int getPositionForSection(int section) {
		for (int i = 0; i < SourceDateList.size(); i++) {
			String sortStr = SourceDateList.get(i).get_NAMEPY();
			char firstChar = sortStr.toUpperCase().charAt(0);
			if (firstChar == section) {
				return i;
			}
		}

		return -1;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - mExitTime) > 2000) {
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				mExitTime = System.currentTimeMillis();
			} else {
				MyApplication.getInstance().quit();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case constantUtil.Num_SelectContactByNoGroup:
				SourceDateList.clear();
				/**
				 * 这里边是刷新的一系列数据准备，准备好后进行刷新
				 **/
				List<ContactInfoBySqlite> listcons=(List<ContactInfoBySqlite>) msg.obj;
				for(ContactInfoBySqlite con:listcons){
					SourceDateList.add(con);
				}
				Log.i("libs", "shuju"+SourceDateList.size());
				// 根据a-z进行排序源数据
				Collections.sort(SourceDateList, pinyinComparator);
				adapterSort.notifyDataSetChanged();
				disMissDialog();
				break;
				case constantUtil.Num_DelContactByID:
					String result= (String)msg.obj;
					if(result.equals("succeed")){
	        			 ContactInfoServise ser = new ContactInfoServise(mContext);
	        			 int id=msg.arg1;
	        			 ser.DelContactByIDTrue(id);
	        			 Toast.makeText(mContext,"删除成功！",Toast.LENGTH_SHORT).show();
		 					SourceDateList.remove(posiont-2);
		 					adapterSort.notifyDataSetChanged();
	        		 }
	        		 else{
	        			 Toast.makeText(getApplication(),"删除失败！",Toast.LENGTH_SHORT).show();
	        		 }
				break;
			default:
				break;
			}
		}
	};
}
